import 'dart:convert';

import 'package:thingskit/apiService/ApiService.dart';

import '../utils/const.dart';

class Mode {
  final int id;
  final String name;
  final String content;

  Mode({required this.id, required this.name, required this.content});
}

class ModeApi extends ApiService {
  ModeApi() : super(thingskitUrl);

  //获取方案列表
  Future<List<Mode>> getModeList() async {
    final response = await getRequest('/debugdevice/mode');
    if (response == null) {
      return [];
    }

    final result = response;

    if (result is! List) {
      print('返回结果不是列表：$result');
      return [];
    }

    final modeList = (result).map<Mode>((item) {
      final map = item as Map<String, dynamic>;

      // 转换 content 字段为 String 类型
      final content = map['content'];
      String contentStr;
      if (content is Map || content is List) {
        contentStr = jsonEncode(content);
      } else {
        contentStr = content?.toString() ?? '{}';
      }

      return Mode(
        id: map['id'] is int ? map['id'] : int.parse(map['id'].toString()),
        name: map['mode_name']?.toString() ?? '未知方案',
        content: contentStr,
      );
    }).toList();
    return modeList;
  }


  //创建方案
  Future<dynamic> createMode(String name, String content) async {
    final response = await postRequest('/debugdevice/mode', {
     name:content,
    });
    if (response == null) {
      return null;
    }
    return response;
  }

  //修改方案名称
  Future<dynamic> updateModeName(int id,String name) async {
    final response = await postRequest('/debugdevice/mode/$id', {
      "name": name,
    });
    if (response == null) {
      return null;
    }
    return response;
  }

  //删除方案
  Future<dynamic> deleteMode(int id) async {
    final response = await deleteRequest('/debugdevice/mode/$id');
    if (response == null) {
      return null;
    }
    return response;
  }

  //查看方案
  Future<dynamic> getOneMode(int id) async {
    final response = await getRequest('/debugdevice/mode/$id');
    if (response == null) {
      return null;
    }
    return response;
  }
}
